package com.jihox.abookpro.getui;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;

import com.igexin.sdk.PushConsts;
import com.jihox.abookpro.HomeChangeActivity;
import com.jihox.abookpro.R;

public class PushReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		switch (bundle.getInt(PushConsts.CMD_ACTION)) {
		case PushConsts.GET_MSG_DATA:
			// 获取透传数据
			byte[] payload = bundle.getByteArray("payload");
			Date generateTime = new Date();
			if (payload != null) {
				String data = "";
				try {
					data = new String(payload,"Utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				sendNotification(context, data, data, generateTime.getTime());
			}
			break;
		default:
			break;
		}
	}
	private void sendNotification(Context context,String content,String title, long when) {
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
		if(when <= 0)
			when = System.currentTimeMillis();
		NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(context);
		Intent intent = new Intent(context, HomeChangeActivity.class);
		intent.putExtra("isNotification", "notification");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		int requestCode = (int) SystemClock.uptimeMillis();
		PendingIntent pendingIntent = PendingIntent.getActivity(
				context, requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		mNotifyBuilder.setLargeIcon(icon).setSmallIcon(R.drawable.icon);
		mNotifyBuilder.setWhen(when);
		mNotifyBuilder.setContentIntent(pendingIntent);
		mNotifyBuilder.setContentTitle(context.getText(R.string.app_name));
		mNotifyBuilder.setContentText(content).setDefaults(Notification.DEFAULT_ALL);
		mNotifyBuilder.setAutoCancel(true); 
		mNotifyBuilder.setSubText(" ");
		mNotifyBuilder.setTicker(title + "\n" + content);
		Notification notification = mNotifyBuilder.build();
		if (notification != null) {
			mNotificationManager.notify(1, notification);
		}
	}
}

